package com.swjd.jingle.fragment;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.cardview.widget.CardView;

import com.swjd.jingle.R;
import com.swjd.jingle.util.Constant;
import com.swjd.jingle.util.Utils;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xui.widget.imageview.RadiusImageView;
import com.xuexiang.xui.widget.toast.XToast;

import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class QRCodeFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.img_head_portrait)
    RadiusImageView imgHeadPortrait;
    @BindView(R.id.tv_nickname)
    TextView tvNickname;
    @BindView(R.id.tv_signature)
    TextView tvSignature;
    @BindView(R.id.img_qrcode)
    ImageView imgQrcode;
    @BindView(R.id.cv_qrcode)
    CardView cvQrcode;
    private boolean isQRCodeCreated = false;

    @Override
    public void initialize() {
    }

    @Override
    public void initViews() {
        tvTitle.setText("二维码名片");
    }

    @Override
    public void initData() {
        try {
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_head_portrait);
            JSONObject json = new JSONObject();
            json.put("username", app.getUserInfo().getUsername());
            json.put("type", Constant.scan_user);
            imgQrcode.setImageBitmap(XQRCode.createQRCodeWithLogo(json.toString(), 300, 300, bitmap));
            isQRCodeCreated = true;
        } catch (Exception e) {
            e.printStackTrace();
            XToast.info(activity,"二维码生成失败!", Toast.LENGTH_SHORT).show();
        }
        cvQrcode.setOnLongClickListener(v -> {
            saveQRCode();
            return false;
        });
    }

    private void saveQRCode() {
        if (isQRCodeCreated) {
            cvQrcode.setDrawingCacheEnabled(true);
            cvQrcode.buildDrawingCache();
            final Bitmap bmp = cvQrcode.getDrawingCache(); // 获取图片
            //保存图片
            Utils.savePicture(activity, cvQrcode, bmp, "card" + System.currentTimeMillis() + ".png");
        } else {
            XToast.info(activity,"请先生成二维码!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_qrcode;
    }


    @Override
    @OnClick(R.id.img_back)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_back:
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        fragmentManager.popBackStack();
                    }
                }, 500);
                break;
        }
    }
}
